/**
 * Created by a1 on 2017/5/25.
 */
var fs = require('fs');
var formidable = require('formidable');
var md5 = require('../models/md5');
var UsernameModel = require('../models/Username');
var svgCaptcha = require('svg-captcha');

exports.login=function(req,res,next){
    if(req.session.username){
        res.redirect('/user');
    }else{
        res.render('login',{
            page:'login'
        });
    }
};
exports.doLogin=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files){
        let {username,password}=fields;
        UsernameModel.findFn({},function(err,result){
            let user=[];
            for(var i=0;i<result.length;i++){
                if(result[i]['username']==username){
                    user.push(result[i]['username']);
                }
            }
            if(user.length==0){
                res.json({code:2,retMsg:'用户名不存在'});
                return;
            }else{
                var md5psw = md5(md5(password).substring(0,9)+md5(password));
                UsernameModel.findSortOne({username:username,password:md5psw},{},function(err,docs){
                    if(docs==null||docs==""||docs==undefined){
                        res.json({code:0,retMsg:'密码错误'});
                        return;
                    }else{
                        req.session.username=username;
                        req.session.uid=docs.uid;
                        res.json({code:1,retMsg:'登录成功'});
                        return;
                    }
                })
            }
        })
    });
};
exports.loginCode=function(req,res){
    var captcha = svgCaptcha.create();
	req.session.logincaptcha = captcha.text;
	res.type('svg');
	res.status(200).send(captcha.data);
};
exports.doLoginCode=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files){
        if(fields.code.toLocaleLowerCase()==req.session.logincaptcha.toLocaleLowerCase()){
            res.json({code:1});
        }else{
            res.json({code:0});
        }
    });
};